#encoding:utf-8
import time, os, logging
from logging.handlers import RotatingFileHandler
from flask import Flask, g
from flask.ext.login import LoginManager
from flask_debugtoolbar import DebugToolbarExtension
from app.ext import mongo
from app.filters import error_handers, register_template_filters
from app.models import Account
from app.views.backend import app as backend_blue
from app.views.front import app as front_blue
from app.views.passport import app as passport_blue
from bson.objectid import ObjectId

login_manager = LoginManager()
login_manager.login_view = "passport.login"

blueprints=(
    (front_blue, ''),
    (passport_blue, '/passport'),
    (backend_blue, ''),
)

@login_manager.user_loader
def load_user(userid):
    print userid
    ac_m = mongo.db.account.find_one({'_id': ObjectId(userid)})
    ac = Account(_id=ac_m['_id'], login_id=ac_m['login_id'], password=ac_m['password'])
    return ac

def register_blueprint(app,blueprints):
    for module,prefix in blueprints:
        app.register_blueprint(module, url_prefix=prefix)

def register_db(app):
    #mongodb
    mongo.init_app(app)


def create_app(config=None):
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'sportxxxxxxxxxxxx'
    toolbar = DebugToolbarExtension(app)
    if config:
        app.config.from_pyfile(config)
        config_logging(app)
        app.config['MONGO_URI'] = '%s%s' %(os.environ['OPENSHIFT_MONGODB_DB_URL'], os.environ['OPENSHIFT_APP_NAME'])



    error_handers(app)
    login_manager.init_app(app,add_context_processor=True)
    register_blueprint(app, blueprints)
    register_template_filters(app)
    register_db(app)
    @app.before_request
    def before_request():
        g.start = time.time()
        g.sitename = u'sports'

    return app


def config_logging(app):
    if app.debug or app.testing:
        return

    formatter = logging.Formatter(
    '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')

    debug_log = os.path.join(app.root_path, app.config['DEBUG_LOG'])
    debug_file_handler = RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10)
    debug_file_handler.setLevel(logging.DEBUG)
    debug_file_handler.setFormatter(formatter)
    app.logger.addHandler(debug_file_handler)

    error_log = os.path.join(app.root_path, app.config['ERROR_LOG'])
    error_file_handler = RotatingFileHandler(error_log, maxBytes=100000, backupCount=10)
    error_file_handler.setLevel(logging.ERROR)
    error_file_handler.setFormatter(formatter)
    app.logger.addHandler(error_file_handler)
